import React, { useState } from "react";

import { Upload } from 'antd';
import { LoadingOutlined, PlusOutlined, CloseCircleOutlined } from '@ant-design/icons';


function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

export default function UploadBox(props) {
    let [ loading, setLoading] = useState(false);
    let [ imageUrl, setUrl] = useState('');

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div className="ant-upload-text">添加上传图片</div>
        </div>
    );
    let handleChangeFile = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            console.log(info)
            setLoading(false);
            setUrl(info.file.response.url);
            props.onChangeFile(info.file.response.url);
        }
    };
    return (
        <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={ props.action }
            beforeUpload={beforeUpload}
            onChange={handleChangeFile}
        >
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
    );
}